// Create and style floating button
const button = document.createElement('button');
button.id = 'audio-navigator-button';
button.textContent = '⏭️';
button.style.bottom = '20px';
button.style.right = '20px';
button.style.zIndex = '9999';
button.style.width = '60px';
button.style.height = '60px';
button.style.borderRadius = '50%';
button.style.backgroundColor = '#4285f4';
button.style.color = 'white';
button.style.border = 'none';
button.style.fontSize = '24px';
button.style.cursor = 'pointer';
button.style.boxShadow = '0 2px 10px rgba(0,0,0,0.2)';

document.body.appendChild(button);

// Main functionality when button is clicked
async function nextAudio() {
  try {
      // Get current page title
    const pageTitle = document.title;
    console.log('Extracted page title:', pageTitle);

    // Find and click the directory button
    // 优化目录按钮选择器，匹配图片中的实际元素结构
    const directoryButton = document.querySelector('.big_subject_catalogue') || 
                          document.querySelector('div[class*="catalogue"] img[alt*="目录"]').parentNode ||
                          document.querySelector('img[alt*="目录"]').closest('div');

    if (directoryButton) {
      directoryButton.click();
      console.log('Directory button clicked');
      // Wait for directory to open
      await new Promise(resolve => setTimeout(resolve, 1000));

      // 查找所有音频项（匹配提供的small_subject_card结构）
      const audioItems = document.querySelectorAll('.small_subject_card');
      console.log('找到音频项数量:', audioItems.length);

      // 搜索当前标题在列表中的位置
      let currentIndex = -1;
      audioItems.forEach((item, index) => {
        const titleElement = item.querySelector('.small_subject_title');
        if (titleElement && titleElement.textContent.includes(pageTitle) && currentIndex === -1) {
          currentIndex = index;
        }
      });

      // 点击下一个音频项的播放按钮
      if (currentIndex !== -1 && currentIndex < audioItems.length - 1) {
        const nextItem = audioItems[currentIndex + 1];
        const playButton = nextItem.querySelector('.ssc_play_icon img') || nextItem.querySelector('.ssc_play_icon');
        if (playButton) {
          playButton.click();
          console.log('已点击下一个音频项:', currentIndex + 1);
        } else {
          nextItem.click();
          console.log('未找到播放按钮，点击音频项本身:', currentIndex + 1);
        }
      } else {
        alert('未找到当前标题或已到达最后一个音频项');
      }
    } else {
      alert('Directory button not found on page');
    }
  } catch (error) {
    console.error('Error:', error);
    alert('An error occurred while processing');
  }
}

// Add event listeners
button.addEventListener('click', nextAudio);
document.addEventListener('keydown', (e) => {
  // Trigger only when space key is pressed and not in input/textarea
  if (e.code === 'Space' && !['INPUT', 'TEXTAREA'].includes(document.activeElement.tagName)) {
    e.preventDefault();
    nextAudio();
  }
});